<template>
  <div>
    <el-drawer
      title="添加商品"
      :visible.sync="drawer"
      direction="btt"
      size="100%"
    >
      <div class="w">
        <el-steps
          :active="active"
          finish-status="success"
          class="jw_margin_bottom"
        >
          <el-step title="步骤 1"></el-step>
          <el-step title="步骤 2"></el-step>
          <el-step title="步骤 3"></el-step>
          <el-step title="步骤 4"></el-step>
        </el-steps>
        <div v-if="active == 0">
          <el-form
            label-position="right"
            label-width="100px"
            :model="spu"
            :rules="spuRules"
          >
            <el-form-item label="商品标题" prop="spuTitle">
              <el-input
                v-model="spu.spuTitle"
                size="small"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="商品副标题" prop="spuSubTitle">
              <el-input
                v-model="spu.spuSubTitle"
                size="small"
                maxlength="50"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="商品类别" prop="categoryId">
              <el-select
                v-model="spu.categoryId"
                placeholder="请选择分类"
                filterable
                size="small"
              >
                <el-option
                  v-for="item in categorys"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId"
                >
                  <span style="float: left">{{ item.categoryName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属店铺">
              <el-input
                v-model="spu.storeName"
                size="small"
                disabled
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="active == 1">
          <!-- 富文本编辑器 -->
          <span class="editor-span">请输入商品描述：</span>
          <div id="editor" style="margin-top: 10px"></div>
        </div>
        <!-- 规格参数填写 -->
        <div v-if="active == 2">
          <el-form
            ref="form"
            :model="genericSpec"
            :rules="rules"
            label-width="130px"
            size="mini"
            label-position="right"
          >
            <el-form-item label="生产许可证编号" prop="n1">
              <el-input v-model="genericSpec.n1" size="small"></el-input>
            </el-form-item>
            <el-form-item label="产品标准号" prop="n2">
              <el-input v-model="genericSpec.n2" size="small"></el-input>
            </el-form-item>
            <el-form-item label="厂名" prop="n3">
              <el-input
                v-model="genericSpec.n3"
                size="small"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="厂址" prop="n4">
              <el-input
                v-model="genericSpec.n4"
                size="small"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="厂家联系方式" prop="n5">
              <el-input
                v-model="genericSpec.n5"
                size="small"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="储藏方法" prop="n6">
              <el-input
                v-model="genericSpec.n6"
                size="small"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="保质期" prop="n7">
              <el-input v-model="genericSpec.n7" size="small">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
            <el-form-item label="包装种类" prop="n8">
              <el-select v-model="genericSpec.n8" automatic-dropdown>
                <el-option label="罐装" value="罐装"> </el-option>
                <el-option label="袋装" value="袋装"> </el-option>
                <el-option label="瓶装" value="瓶装"> </el-option>
                <el-option label="盒装" value="盒装"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否有机食品" prop="n9" automatic-dropdown>
              <el-select v-model="genericSpec.n9">
                <el-option label="是" value="是"> </el-option>
                <el-option label="否" value="否"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="active == 3">
          <div v-if="paInputComp">
            <div class="sku-select-div">
              <span
                style="margin-right: 10px; display: inline-block; width: 80px"
                >口味</span
              >
              <el-select
                class="e-select-width"
                v-model="taste"
                placeholder="请选择或输入添加口味选项"
                multiple
                filterable
                allow-create
                default-first-option
                size="small"
              >
                <el-option
                  v-for="item in tasteOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div class="sku-select-div">
              <span
                style="margin-right: 10px; display: inline-block; width: 80px"
                >净含量</span
              >
              <el-select
                class="e-select-width"
                v-model="netContent"
                placeholder="请选择或输入添加净含量选项"
                multiple
                filterable
                allow-create
                default-first-option
                size="small"
              >
                <el-option
                  v-for="item in netContentOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <span style="padding: 0px 5px">克</span>
            </div>
            <div class="sku-select-div">
              <span
                style="margin-right: 10px; display: inline-block; width: 80px"
                >品质等级</span
              >
              <el-select
                class="e-select-width"
                v-model="level"
                placeholder="请选择或输入添加品质等级选项"
                multiple
                filterable
                allow-create
                default-first-option
                size="small"
              >
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <el-button type="primary" size="small" @click="comInputSpec"
              >输入参数完成</el-button
            >
          </div>
          <div v-else style="max-height: 400px; overflow-y: auto">
            <div v-for="(spec, index) in skuSpec" :key="index">
              <el-card class="box-card" style="margin-bottom: 10px">
                <div slot="header" class="clearfix">
                  <span>{{ "sku参数设置" + (index + 1) }}</span>
                  <el-link
                    :type="spec.ifUse ? 'danger' : 'primary'"
                    @click="change(spec)"
                    style="float: right; padding: 3px 0"
                    >{{ spec.ifUse ? "缺货" : "有货" }}</el-link
                  >
                </div>
                <div class="spec-input" v-if="spec.ifUse">
                  <div>
                    <span>口味</span>
                    <label>{{ spec.taste }}</label>
                  </div>
                  <div>
                    <span>净含量/(克)</span>
                    <label>{{ spec.netContent }}</label>
                  </div>
                  <div>
                    <span>品质等级</span>
                    <label>{{ spec.level }}</label>
                  </div>
                  <!-- 图片上传 -->
                  <div>
                    <span>图片</span>
                    <el-upload
                      :action="''"
                      :show-file-list="false"
                      :limit="1"
                      :auto-upload="false"
                      accept="image/jpeg,image/jpg,image/png"
                      :on-change="
                        (file) => {
                          handleAvatarChange(file, skuSpec, index);
                        }
                      "
                    >
                      <el-image
                        style="width: 100px; height: 100px"
                        :src="spec.imgUrl"
                        fit="cover"
                      >
                        <div
                          slot="error"
                          class="imageClass"
                          style="
                            width: 98px;
                            height: 98px;
                            border: dashed 1px #8c939d;
                            color: #8c939d;
                          "
                        >
                          <i
                            class="el-icon-plus avatar-uploader-icon"
                            style="line-height: 100px"
                          ></i>
                        </div>
                      </el-image>
                    </el-upload>
                  </div>

                  <div>
                    <span>金额</span>
                    <el-input-number
                      size="small"
                      :precision="2"
                      v-model="spec.price"
                      :min="1"
                      :max="10000"
                      label="金额"
                      :disabled="!spec.ifUse"
                    ></el-input-number>
                  </div>
                </div>
                <div v-else style="color: red">此商品缺货中</div>
              </el-card>
            </div>
          </div>
        </div>
        <el-button
          v-if="active != 0"
          class="stepButtonPrevious"
          type="primary"
          @click="previous()"
          >上一步
        </el-button>
        <el-button
          class="stepButton"
          type="primary"
          @click="next"
          slot="reference"
          >{{ buttonInfo }}
        </el-button>
      </div>
    </el-drawer>
    <el-table
      :data="spuList"
      style="width: 1002px; margin: 0 auto"
      max-height="352"
      stripe
      border
      :header-cell-style="headerStyle"
    >
      <!-- ID项 -->
      <el-table-column prop="spuId" label="ID" width="250"> </el-table-column>
      <!-- 名称项 -->
      <el-table-column prop="spuTitle" label="标题" width="250">
      </el-table-column>
      <!-- 开店时间 -->
      <el-table-column prop="spuCreateTimeStr" label="创建时间" width="250">
      </el-table-column>
      <!-- 操作栏 -->
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button
            type="primary"
            @click="openEditButton(scope.$index, spuList)"
            icon="el-icon-edit"
            size="small"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            @click="deleteRow(scope.$index, spuList)"
            size="small"
            type="primary"
            icon="el-icon-delete"
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button
      type="primary"
      size="medium"
      plain
      round
      @click="addGood"
      class="addButton"
      >添加商品</el-button
    >
  </div>
</template>

<script>
import E from "wangeditor";
export default {
  data() {
    return {
      // 通用规格参数输入限制
      rules: {
        n1: [
          { required: true, message: "请输入生产许可证编号", trigger: "blur" },
        ],
        n2: [{ required: true, message: "请输入产品标准号", trigger: "blur" }],
        n7: [{ required: true, message: "请输入保质期天数", trigger: "blur" }],
        n8: [
          { required: true, message: "请选择包装方种类", trigger: "change" },
        ],
      },
      // sku独有规格参数选择
      taste: [],
      netContent: [],
      level: [],
      tasteOptions: [
        { lable: "原味", value: "原味" },
        { lable: "奶油味", value: "奶油味" },
        { lable: "盐焗味", value: "盐焗味" },
      ],
      netContentOptions: [
        { lable: "500", value: "500" },
        { lable: "1000", value: "1000" },
        { lable: "2000", value: "2000" },
        { lable: "3000", value: "3000" },
        { lable: "4000", value: "4000" },
        { lable: "5000", value: "5000" },
      ],
      levelOptions: [
        { lable: "普通", value: "普通" },
        { lable: "优质", value: "优质" },
        { lable: "精品", value: "精品" },
        { lable: "特级", value: "特级" },
      ],
      skuSpec: [],
      // spu输入规则限制
      spuRules: {
        spuTitle: [{ required: true, message: "请输入标题", trigger: "blur" }],
        spuSubTitle: [
          { required: true, message: "请输入副标题", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "change" },
        ],
      },
      // 富文本编辑器
      editor: null,
      editorContent: null,
      //spu属性
      spu: {
        storeName: "自营",
        spuTitle: "",
        spuSubTitle: "",
      },
      //类别
      categorys: [],
      genericSpec: {
        n3: "疆味食品有限责任公司",
        n4: "新疆省xxx市xxx县xxxxx",
        n5: "00000000000",
        n6: "请存放在阴凉干燥处",
      },
      // drawer是否开启
      drawer: false,
      // 添加商品的按钮信息
      buttonInfo: "下一步",
      // 当前激活步骤，0为第一步
      active: 0,
      // sku参数未输入完成
      paInputComp: true,
      skuSpecNum: 0,
      // spuList
      spuList: [],
    };
  },
  created() {
    this.getSpus();
  },
  methods: {
    headerStyle() {
      return "color: #000;background-color: #c5464a;height:60px;";
    },
    getSpus() {
      let _this = this;
      this.$http.get("jw-spu/list").then((response) => {
        _this.spuList = response.data.result;
      });
    },
    addGood() {
      this.drawer = true;
      this.getCategorys();
    },
    getCategorys() {
      this.$http.get("jw-category/findAll").then((response) => {
        this.categorys = response.data.result;
      });
    },
    // 点击下一步时触发
    next() {
      if (this.active == 0) {
        if (
          this.spu.categoryId == null ||
          this.spu.spuSubTitle == "" ||
          this.spu.spuTitle == ""
        ) {
          return;
        }
      }
      if (this.active == 2) {
        var count = 0;
        for (const key in this.genericSpec) {
          count++;
          if (this.genericSpec[key] == "") {
            count = -1;
            break;
          }
        }
        if (count != 9) {
          return;
        }
      }
      if (this.active == 3) {
        if (!this.specShowErrorMsg()) {
          return;
        }
        if (this.skuSpec.length == 0) {
          this.$message.error("请生成参数模板并填写参数");
          return;
        }
        this.skuSpec.forEach((sku) => {
          if (typeof sku.price == "undefined") {
            this.$message.error("存在模板金额未填写，无法提交");
            return;
          }
        });
      }
      if (this.active++ >= 3) this.active = 3;
      if (this.buttonInfo == "提交") {
        var data = {};
        // 设置spu参数
        this.spu.storeId = 0;
        data.spu = this.spu;
        // 设置spuDetail参数
        var spuDetail = {};
        spuDetail.spuDescription = this.editorContent;
        spuDetail.spuGenericSpec = this.genericSpec;
        spuDetail.spuSpecialSpec = {
          n10: this.taste,
          n11: this.netContent,
          n12: this.level,
        };
        data.spuDetail = spuDetail;
        // 设置sku参数
        data.sku = this.skuSpec;
        this.$http.post("jw-spu/add", data).then((response) => {
          this.$message.success("提交成功");
          this.drawer = false;
        });
      }
      if (this.active == 3) {
        this.buttonInfo = "提交";
        return;
      }
    },
    // 点击上一步时触发
    previous() {
      if (this.active != 0) {
        this.active--;
      }
      if (this.buttonInfo == "提交") {
        this.buttonInfo = "下一步";
      }
    },
    // sku参数输入完成后生成动态的可输入表格
    comInputSpec() {
      if (!this.specShowErrorMsg()) {
        return;
      }
      this.paInputComp = false;
      // 生成动态表格
      let num = 0;
      for (let p = 0; p < this.netContent.length; p++) {
        for (let i = 0; i < this.taste.length; i++) {
          for (let j = 0; j < this.level.length; j++) {
            var sku = {};
            sku.level = this.level[j];
            sku.taste = this.taste[i];
            sku.netContent = this.netContent[p];
            sku.ifUse = true;
            this.skuSpec.push(sku);
            num++;
          }
        }
      }
      this.skuSpecNum = num;
    },
    specShowErrorMsg() {
      if (this.netContent.length == 0) {
        this.$message.error("净含量参数不能为空");
        return false;
      }
      if (this.taste.length == 0) {
        this.$message.error("口味参数不能为空");
        return false;
      }
      if (this.level.length == 0) {
        this.$message.error("品质等级参数不能为空");
        return false;
      }
      return true;
    },
    change(spec) {
      console.log(spec);
      spec.ifUse = !spec.ifUse;
    },
    // 上传图片
    handleAvatarChange(file, specList, index) {
      const isIMAGE =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt1M = file.size / 1024 / 1024 < 1;
      let _this = specList[index];
      let __this = this;
      _this.uploadFile = file;
      _this.type = _this.uploadFile.name.substring(
        _this.uploadFile.name.lastIndexOf(".")
      );
      if (!isIMAGE) {
        this.$message.error("上传文件只能是图片格式!");
        this.reload();
        return false;
      }
      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 1MB!");
        this.reload();
        return false;
      }
      let reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function (e) {
        _this.imgUrl = this.result;
        __this.$set(__this.skuSpec, index, _this);
      };
    },
  },
  watch: {
    // 监控active属性激活富文本创建
    active(n, o) {
      const _this = this;
      if (n == 1) {
        // 富文本上传图片
        this.$nextTick(() => {
          this.editor = new E("#editor");
          this.editor.config.height = 300;
          this.editor.config.uploadImgAccept = ["jpg", "jpeg", "png"];
          this.editor.config.onchange = (html) => {
            this.editorContent = html;
          };
          this.editor.config.customUploadImg = function (
            resultFiles,
            insertImgFn
          ) {
            // resultFiles 是 input 中选中的文件列表
            // insertImgFn 是获取图片 url 后，插入到编辑器的方法
            resultFiles.forEach((img) => {
              var type = img.type;
              var reader = new FileReader();
              reader.readAsDataURL(img);
              reader.onload = () => {
                _this.$http
                  .post("file/upload", { file: reader.result, type: type })
                  .then((response) => {
                    insertImgFn(response.data.result);
                  });
              };
            });
            // 上传图片，返回结果，将图片插入到编辑器中
          };
          this.editor.create(); // 创建富文本实例
          this.editor.txt.html(this.editorContent);
        });
      }
    },
  },
};
</script>

<style scoped>
.w {
  width: 1100px;
  margin: 0 auto;
}
.stepButton {
  position: absolute;
  bottom: 20px;
  right: 80px;
}
.stepButtonPrevious {
  position: absolute;
  bottom: 20px;
  right: 180px;
}
.jw_margin_bottom {
  margin-bottom: 20px;
}
.inputWidth {
  width: 400px;
}
.el-form {
  margin-top: 30px;
  margin-left: 50px;
}
.editor-span {
  margin-bottom: 10px;
  color: rgb(136, 134, 134);
}
.e-select-width {
  width: 88%;
}
.sku-select-div {
  margin-bottom: 10px;
}
.spec-input .el-input {
  margin: 5px 0px;
  width: 80%;
}
.spec-input span {
  margin-bottom: 3px;
  margin-right: 5px;
  width: 100px;
  display: inline-block;
}
.imageClass {
  color: #8c939d;
  border: dashed 1px #8c939d;
  line-height: 100px;
}
.addButton {
  margin-top: 12px !important;
  float: right;
  right: 30px;
}
</style>